﻿#region Copyright (C) 2012 Francisco Monteiro
/*

Morpheme
Copyright (C) 2012 Francisco Monteiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

http://code.google.com/p/morpheme-tumblr-theme/

*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TumblrAPI {
	public static class TumblrAPIv2 {

		public const string API_URL = "http://api.tumblr.com/v2";

		public class xpto {
			public class TumblrResponse {
				public TumblrBlog Blog { get; set; }
				public TumblrPost[] Posts { get; set; }
				public int Total_Posts { get; set; }
			}

			public TumblrMeta Meta { get; set; }
			public TumblrResponse Response { get; set; }
		}

		public enum TumblrPostType {
			text,
			photo,
			quote,
			link,
			chat,
			audio,
			video,
			answer,

			none
		}

		public class TumblrMeta {
			public int Status { get; set; }
			public string Msg { get; set; }
		}
		public class TumblrBlog {
			public string Title { get; set; }
			public long Posts { get; set; }
			public string Name { get; set; }
			public string Url { get; set; }
			public long Updated { get; set; }
			public string Description { get; set; }
			public bool Ask { get; set; }
			public bool Ask_Anon { get; set; }
			public long Likes { get; set; }
		}
		public class TumblrPost {

			public class TumblrPhotos {

				public class TumblrPhoto {
					public int Width { get; set; }
					public int Height { get; set; }
					public string Url { get; set; }
				}

				public string Caption { get; set; }
				public TumblrPhoto[] Alt_Sizes { get; set; }
			}
			public class TumblrChat {
				public string Label { get; set; }
				public string Name { get; set; }
				public string Phrase { get; set; }
			}
			public class TumblrVideo {
				public int Width { get; set; }
				public string Embed_Code { get; set; }
			}

			public string Blog_Name { get; set; }
			public string Id { get; set; }
			public string Post_Url { get; set; }
			public TumblrPostType Type { get; set; }
			public DateTime Date { get; set; }
			public long Timestamp { get; set; }
			public string Format { get; set; }
			public string Reblog_Key { get; set; }
			public string[] Tags { get; set; }
			public long Note_Count { get; set; }

			// <photo>
			public TumblrPhotos[] Photos { get; set; }
			// </photo>

			// <quote>
			public string Text { get; set; }
			public string Source { get; set; }
			// </quote>

			// <link>
			public string Url { get; set; }
			public string Description { get; set; }
			// </link>

			// <chat>
			public TumblrChat[] Dialogue { get; set; }
			// </chat>

			// <audio>
			public string Id3_Title { get; set; }
			public long Plays { get; set; }
			// </audio>

			// <answer>
			public string Asking_Name { get; set; }
			public string Asking_Url { get; set; }
			public string Question { get; set; }
			public string Answer { get; set; }
			// </answer>

			// <SHARED: video, audio>
			//public string Player { get; set; } // audio
			//public TumblrVideo[] Player { get; set; } // video
			public object Player { get; set; } // ToDos: here! looks really bad!

			public TumblrVideo[] VideoPlayer {
				get {

					Newtonsoft.Json.Linq.JArray aux = (Newtonsoft.Json.Linq.JArray)Player;
					TumblrVideo[] output = new TumblrVideo[aux.Count];
					for (int i = 0; i < aux.Count; i++) {
						output[i] = JsonConvert.DeserializeObject<TumblrVideo>(aux[i].ToString());
					}

					return output;
				}
			}
			public string AudioPlayer {
				get {
					return (string)Player;
				}
			}
			// </SHARED: video, audio>

			// <SHARED: quote, audio, video>
			public string Source_Title { get; set; }
			// </SHARED: quote, audio, video>

			// <SHARED: photo, audio, video>
			public string Caption { get; set; }
			// </SHARED: photo, audio, video>

			// <SHARED: quote, audio, video>
			public string Source_Url { get; set; }
			// </SHARED: quote, audio, video>

			// <SHARED: text, link, chat>
			public string Title { get; set; }
			// </SHARED: text, link, chat>

			// <SHARED: text, chat>
			public string Body { get; set; }
			// </SHARED: text, chat>
		}

		public static TumblrBlog ReadInfo(
			string url
		) {
			string jsonUrl = string.Format(
				"{0}/blog/{1}/info?api_key={2}",
				API_URL,
				url,
				utils.TumblrAPIv2Key
			);
			string jsonString;
#if TEST
			jsonString = @"{
				""meta"": {
				""status"": 200,
				""msg"": ""OK""
			},
			""response"": {
				""blog"": {
					""title"": ""David's Log"",
					""posts"": 3456,
					""name"": ""david"",
					""url"": ""http:\/\/david.tumblr.com\/"",
					""updated"": 1308953007,
					""description"": ""<p><strong>Mr. Karp<\/strong> is tall and skinny, with
						unflinching blue eyes a mop of brown hair.\r\n
						He speaks incredibly fast and in complete paragraphs.</p>"",
					""ask"": true,
					""ask_anon"": false,
					""likes"": 12345
				}
			}
		}";
#else
			jsonString = utils.ReadURL_ToString(jsonUrl);
#endif

			TumblrBlog output;
			JObject json;
#if !DEBUG
			try {
#endif
			json = JObject.Parse(jsonString);

			TumblrMeta meta = JsonConvert.DeserializeObject<TumblrMeta>(
				json["meta"].ToString()
			);
			if (meta.Status != 200) {
				return null;
			}

			output = JsonConvert.DeserializeObject<TumblrBlog>(
				json["response"]["blog"].ToString()
			);

#if !DEBUG
			} catch {
				// ToDos: here!
				return null;
			}
#endif

			return output;
		}

		public static TumblrPost[] ReadPosts(
			string url,
			TumblrPostType postType,
			string id,
			string tag,
			int limit,
			int offset,
			string format
		) {
			string jsonUrl = string.Format(
				"{0}/blog/{1}/posts{2}?api_key={3}",
				API_URL,
				url,
				((postType != TumblrPostType.none)
					? string.Format("/{0}", postType.ToString())
					: ""
				),
				utils.TumblrAPIv2Key
			);
			string jsonString;
#if TEST
			#region jsonString = ...;
			jsonString = @"{
				""meta"": {
				""status"": 200,
				""msg"": ""OK""
			},
				""response"": {
					""posts"": [
						{
							""blog_name"": ""citriccomics"",
							""id"": 1,
							""post_url"": ""http:\/\/citriccomics.tumblr.com\/post\/3507845453"",
							""type"": ""text"",
							""date"": ""2011-02-25 20:27:00 GMT"",
							""timestamp"": 1298665620,
							""format"": ""html"",
							""reblog_key"": ""b0baQtsl"",
							""tags"": [
								""tumblrize"",
								""milky dog"",
								""mini comic""
							],
							""note_count"": 14,
							""title"": ""Milky Dog"",
							""body"": ""<p><img src=\""http:\/\/media.tumblr.com\/tumblr_lh6x8d7LBB1qa6gy3.jpg\""\/><a href=\""http:\/\/citriccomics.com\/blog\/?p=487\"" target=\""_blank\"">TO READ THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired bysomething <a href=\""http:\/\/gunadie.com\/naomi\""target=\""_blank\"">Naomi Gee<\/a> wrote on twitter, I really liked the hash tag <a href=\""http:\/\/twitter.com\/search?q=%23MILKYDOG\"" target=\""_blank\"">#milkydog<\/a>and quickly came up with a little comic about it. You can (and should) follow Naomi on twitter <a href=\""http:\/\/twitter.com\/ngun\"" target=\""_blank\"">@ngun<\/a> I'm ontwitter as well <a href=\""http:\/\/twitter.com\/weflewairplanes\""target=\""_blank\"">@weflewairplanes<\/a><\/p>\n\nAlso, if youâ€™re a Reddit user (or even if you're not) I submitted this there, if you could up vote it I'd be super grateful just <a href=\""http:\/\/tinyurl.com\/5wj3tqz\"" target=\""_blank\"">CLICK HERE<\/a>""
						|},{
							""blog_name"": ""derekg"",
							""id"": 7431599279,
							""post_url"": ""http:\/\/derekg.org\/post\/7431599279"",
							""type"": ""photo"",
							""date"": ""2011-07-09 22:09:47 GMT"",
							""timestamp"": 1310249387,
							""format"": ""html"",
							""reblog_key"": ""749amggU"",
							""tags"": [],
							""note_count"": 18,
							""caption"": ""<p>my arm is getting tired.<\/p>"",
							""photos"": [
									{
										""caption"": """",
										""alt_sizes"": [
											{
												""width"": 1280,
												""height"": 722,
												""url"": ""http:\/\/derekg.org\/photo\/1280\/7431599279\/1\/tumblr_lo36wbWqqq1qanqww""
											},{
												""width"": 500,
												""height"": 282,
												""url"": ""http:\/\/30.media.tumblr.com\/tumblr_lo36wbWqqq1qanqwwo1_500.jpg""
											},{
												""width"": 400,
												""height"": 225,
												""url"": ""http:\/\/29.media.tumblr.com\/tumblr_lo36wbWqqq1qanqwwo1_400.jpg""
											},{
												""width"": 250,
												""height"": 141,
												""url"": ""http:\/\/26.media.tumblr.com\/tumblr_lo36wbWqqq1qanqwwo1_250.jpg""
											},{
												""width"": 100,
												""height"": 56,
												""url"": ""http:\/\/24.media.tumblr.com\/tumblr_lo36wbWqqq1qanqwwo1_100.jpg""
											},{
												""width"": 75,
												""height"": 75,
												""url"": ""http:\/\/30.media.tumblr.com\/tumblr_lo36wbWqqq1qanqwwo1_75sq.jpg""
											}
										]
									}
								]
							},
							{
							""blog_name"": ""museumsandstuff"",
							""id"": 4742980381,
							""post_url"": ""http:\/\/museumsandstuff.tumblr.com\/post\/4742980381"",
							""type"": ""quote"",
							""date"": ""2011-04-19 08:52:34 GMT"",
							""timestamp"": 1303203154,
							""format"": ""html"",
							""reblog_key"": ""KLA85e6c"",
							""tags"": [],
							""note_count"": 23,
							""source_url"": ""http:\/\/museumtwo.blogspot.com\/2011\/04\/guest-post-convivial-museum-photo-essay.html"",
							""source_title"": ""museumtwo.blogspot.com"",
							""text"": ""Why do visitors still report discomfort, confusion, elitism, exclusion?"",
							""source"": ""<a href=\""http:\/\/museumtwo.blogspot.com\/2011\/04\/guest-post-convivial-museum-photo-essay.html\"" target=\""_blank\"">Museum 2.0: Guest Post: The Convivial Museum Photo Essay<\/a> (via <a href=\""http:\/\/www.joshrobinson.org\/\""target=\""_blank\"">joshrobinsonblog<\/a>)""
							},{
							""blog_name"": ""travellingcameraclub"",
							""id"": 688472164,
							""post_url"": ""http:\/\/travellingcameraclub.com\/post\/688472164"",
							""type"": ""link"",
							""date"": ""2010-06-11 23:17:08 GMT"",
							""timestamp"": 1276298228,
							""format"": ""html"",
							""reblog_key"": ""RWhJJWia"",
							""tags"": [],
							""note_count"": 9,
							""title"": ""Esther Aarts Illustration | News and Blog: Faq: How do you make those marker doodles?"",
							""url"": ""http:\/\/blog.estadiezijn.nl\/post\/459075181\/faq-how-do-you-make-those-marker-doodles"",
							""description"": ""<blockquote>\n<p>On my Ipad, of course!<\/p> <p>Nothing better than the latest technology to get the job done. Look at all my apps!<\/p> <p><img height=\""555\"" width=\""500\"" src=\""http:\/\/farm5.static.flickr.com\/4006\/4445161463_31da0327c2_o.jpg\"" alt=\""my iPad\""\/><\/p> <p>My favourite markers are an Edding 400, a Sharpie and a Copic Ciao. The white gouache is from Dr Martins and does a decent job covering up whatever needs to be covered up, and flows.<\/p><\/blockquote>""
							},{
							""blog_name"": ""david"",
							""id"": 5845345725,
							""post_url"": ""http:\/\/www.davidslog.com\/5845345725\/if-youre-okay-with-it-destroying-tumblr"",
							""type"": ""chat"",
							""date"": ""2011-05-25 22:32:00 GMT"",
							""timestamp"": 1306362720,
							""format"": ""html"",
							""reblog_key"": ""wlxAsElf"",
							""tags"": [],
							""note_count"": 114,
							""title"": null,
							""body"": ""David: http://staff.tumblr.com/post/5845153911
							[draft] Topherchris: are you freaking serious\r\n
							David: If you're okay with it - I'd love to :)\r\n
							Topherchris: i'm okay with it, if you're okay with
							it destroying tumblr"",
							""dialogue"": [
							{
							""label"": ""David:"",
							""name"": ""David"",
							""phrase"": ""http://staff.tumblr.com/post/5845153911 [draft]\r"",
							},{
							""label"": ""Topherchris:"",
							""name"": ""Topherchris"",
							""phrase"":""are you freaking serious\r""
							},{
							""label"": ""David:"",
							""name"": ""David"",
							""phrase"": ""If you're okay with it - I'd love to :)""
							},{
							""label"": ""Topherchris:"",
							""name"": ""Topherchris"",
							""phrase"": ""i'm okay with it, if you're okay with it destroying tumblr"",
							}
							]
							},{
							""blog_name"": ""derekg"",
							""id"": 5578378101,
							""post_url"": ""http:\/\/derekg.org\/post\/5578378101/otis-redding"",
							""type"": ""audio"",
							""date"": ""2011-05-17 16:21:05 GMT"",
							""timestamp"": 1305649265,
							""format"": ""html"",
							""reblog_key"": ""Wa65rR5l"",
							""tags"": [],
							""note_count"": 3,
							""source_url"": ""http:\/\/soundcloud.com\/mariam-cabal\/otis-redding"",
							""source_title"": ""SoundCloud \/ Mariam Caballero"",
							""id3_title"": ""Otis Redding - Cigarettes And Coffee"",
							""caption"": ""<p>Otis Redding never fails me.\u00a0<\/p>"",
							""player"": ""<embed type=\""application\/x-shockwave-flash\""
							src=\""http:\/\/assets.tumblr.com\/swf\/audio_player.swf?audio_file=http:\/\/www.tumblr.com\/audio_file\/5578378101\/tumblr_llclf5oDKZ1qanqww&color=FFFFFF&logo=soundcloud\""
							height=\""27\"" width=\""207\"" quality=\""best\""><\/embed>"",
							""plays"": 1576
							},{
							""blog_name"": ""john"",
							""id"": 6522991678,
							""post_url"": ""http:\/\/john.io\/post\/6522991678"",
							""type"": ""video"",
							""date"": ""2011-06-14 15:51:21 GMT"",
							""timestamp"": 1308066681,
							""format"": ""html"",
							""reblog_key"": ""sWRdVJrI"",
							""tags"": [],
							""note_count"": 17,
							""source_url"": ""http:\/\/www.WatchMojo.com"",
							""source_title"": ""WatchMojo.com"",
							""caption"": ""<p><a href=\""http:\/\/foreverneilyoung.tumblr.com\/post\/6522738445\"" target=\""_blank\"">foreverneilyoung<\/a>:
							<\/p>\n<blockquote>\n<p><a href=\""http:\/\/watchmojo.tumblr.com\/post\/6521201320\"" target=\""_blank\"">watchmojo<\/a>:<\/p>\n
							<blockquote>\n<p>Neil Young\u2019s live album \u201cA Treasure\u201d is available today. To celebrate, we take a look at the
							life and career of the Canadian singer-songwriter.
							<\/p>\n<\/blockquote>\n<p>Neil 101 for you new fans out
							there.<\/p>\n<\/blockquote>\n<p><strong>If you don't
							know\/appreciate Neil Young's impressive body of work,
							this will help<\/strong><\/p>"",
							""player"": [
							{
							""width"": 250,
							""embed_code"": ""<object width=\""248\"" height=\""169\""><param
							name=\""movie\"" value=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&showinfo=0&fs=1\""><\/param><param name=\""wmode\""
							value=\""transparent\""><\/param><param name=\""
							allowFullScreen\"" value=\""true\""><\/param><embed
							src=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&showinfo=0&fs=1\"" type=\""application\/x-shockwave-flash\""
							width=\""248\"" height=\""169\"" allowFullScreen=\""true\""
							wmode=\""transparent\""><\/embed><\/object>""
							},
							{
							""width"": 400,
							""embed_code"": ""<object width=\""400\"" height=\""251\"">
							<param name=\""movie\"" value=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&showinfo=0&fs=1\""><\/param><param name=\""wmode\"" value=\""transparent\""><\/param><param name=\""allowFullScreen\"" value=\""true\""><\/param><embed src=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&showinfo=0&fs=1\"" type=\""application\/x-shockwave-flash\"" width=\""400\"" height=\""251\""
							allowFullScreen=\""true\"" wmode=\""transparent\"">
							<\/embed><\/object>""
							},
							{
							""width"": 500,
							""embed_code"": ""<object width=\""500\"" height=\""305\""><param
							name=\""movie\"" value=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&
							showinfo=0&fs=1\""><\/param><param name=\""wmode\""
							value=\""transparent\""><\/param><param name=\""
							allowFullScreen\"" value=\""true\""><\/param><embed
							src=\""http:\/\/www.youtube.com\/v\/4Q1aI7xPo0Y&rel=0&egm=0&showinfo=0&fs=1\""
							type=\""application\/x-shockwave-flash\"" width=\""500\""
							height=\""305\"" allowFullScreen=\""true\""
							wmode=\""transparent\""><\/embed><\/object>""
							}
							]
							},{
							""blog_name"": ""david"",
							""id"": 7504154594,
							""post_url"": ""http://www.davidslog.com/7504154594"",
							""type"": ""answer"",
							""date"": ""2011-07-11 20:24:14 GMT"",
							""timestamp"": 1310415854,
							""format"": ""html"",
							""reblog_key"": ""HNvqLd5G"",
							""tags"": [],
							""asking_name"": ""aperfectfacade"",
							""asking_url"": ""http://aperfectfacade.tumblr.com/"",
							""question"": ""I thought Tumblr started in 2007, yet you
							have posts from 2006?"",
							""answer"": ""<p>Good catch! Tumblr <strong>launched</strong> in
							February 2007. We were testing it for a few months before
							then.</p>\n<p><strong>Tumblr Trivia:</strong> Before Tumblr,
							my blog (davidslog.com) was a manually edited, single page,
							HTML tumblelog.</p>""
							}


							],
							""total_posts"": 2
							}
							}";
			#endregion
#else
			jsonString = utils.ReadURL_ToString(jsonUrl);
#endif

			TumblrPost[] output;
			JObject json;
#if !DEBUG
			try {
#endif

			json = JObject.Parse(jsonString);

			TumblrMeta meta = JsonConvert.DeserializeObject<TumblrMeta>(
				json["meta"].ToString()
			);
			if (meta.Status != 200) {
				return null;
			}

			IList<JToken> results = json["response"]["posts"].Children().ToList();
			output = new TumblrPost[results.Count];
			for (int i = 0; i < results.Count; i++) {
				output[i] = JsonConvert.DeserializeObject<TumblrPost>(
					results[i].ToString()
				);
			}

#if !DEBUG
			} catch {
				// ToDos: here!
				return null;
			}
#endif

			return output;
		}
	}
}
